﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Helpers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Security;

namespace MJTop_WebService.Core.Filter
{
    /// <summary>
    /// 检验登陆和权限的filter
    /// </summary>
    [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
    public class BasicAuthorize : AuthorizeAttribute
    {
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            //Basic 认证请求头
            var authorization = actionContext.Request.Headers.Authorization;
            //是否存在允许 匿名
            if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Any()
                || actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Any())
            {
                base.OnAuthorization(actionContext);

            }//Basic 认证请求头 有数据
            else if (authorization != null && !string.IsNullOrWhiteSpace(authorization.Parameter))
            {
                ValidateTicket(authorization.Parameter, actionContext);
            }
            else
            {
                this.HandleUnauthorizedRequest(actionContext);
            }
        }

        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            //返回没有授权
            //base.HandleUnauthorizedRequest(actionContext);
            //actionContext.Response.Content = new StringContent(Json.Encode(Retful.CreateFail("服务端拒绝访问：你没有权限，或者掉线了！")), Encoding.UTF8, "application/json");

            //告诉浏览器要验证
            var challengeMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            //权限信息放在basic
            challengeMessage.Headers.Add("WWW-Authenticate", "Basic");
            throw new HttpResponseException(challengeMessage);
        }

        private void ValidateTicket(string parameter, HttpActionContext actionContext)
        {
            try
            {
                string userData = string.Empty;
                if (!Regex.IsMatch(parameter, @"^[A-Z0-9]+$", RegexOptions.Compiled))//浏览器弹窗 用户输入的账号/密码登陆 Base64编码
                {
                    userData = Encoding.UTF8.GetString(Convert.FromBase64String(parameter)).Replace(":", "&");
                    //查询数据库 验证 账号密码,然后处理授权

                    base.IsAuthorized(actionContext);
                }
                else
                {
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(parameter);
                    if (ticket.Expired)
                    {
                        base.HandleUnauthorizedRequest(actionContext);
                        actionContext.Response.Content = new StringContent(Json.Encode(Retful.CreateFail("服务端拒绝访问：你没有权限，授权票据已经过期！")), Encoding.UTF8, "application/json");
                    }
                    else
                    {
                        userData = ticket.UserData;
                        //查询数据库 验证 账号密码,然后处理授权

                        base.IsAuthorized(actionContext);
                    }
                }

            }
            catch (Exception ex)
            {
                base.HandleUnauthorizedRequest(actionContext);//返回没有授权
                actionContext.Response.Content = new StringContent(Json.Encode(Retful.CreateFail(ex.Message)), Encoding.UTF8, "application/json");
            }
        }
    }
}